package cn.eva.service.Impl.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.eva.common.LayuiTableResult;
import cn.eva.common.ResultJosn;
import cn.eva.dao.EvaTeacherMapper;
import cn.eva.dao.EvaTeacherVoMapper;
import cn.eva.dao.SysRoleMapper;
import cn.eva.dao.SysUserRoleMapper;
import cn.eva.entity.EvaTeacher;
import cn.eva.entity.EvaTeacherVo;
import cn.eva.entity.SysRole;
import cn.eva.entity.SysUserRoleKey;
import cn.eva.example.EvaTeacherExample;
import cn.eva.example.EvaTeacherExample.Criteria;
import cn.eva.example.SysRoleExample;
import cn.eva.example.SysUserRoleExample;
//import cn.eva.example.EvaTeacherExample.Criteria;
import cn.eva.service.admin.SysTeacherService;
import cn.eva.service.admin.UserRoleService;
import cn.eva.utils.UUIDUtils;

@Service
public class SysTeacherServiceImpl implements SysTeacherService {

    @Autowired
    private EvaTeacherMapper teacherMapper;

    @Autowired
    private EvaTeacherVoMapper teacherVoMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * @Tilte 新增老师
     */
    @Override
    @Transactional
    public ResultJosn add(EvaTeacher teacher) {
        List<EvaTeacher> list = new ArrayList<>();
        if (null != this.checkTeacherNo(teacher.gettNo())) {
            throw new IllegalArgumentException(teacher.gettNo() + "已存在！");
        }
        teacher.settId(UUIDUtils.getUUID());
        teacher.settPass(passwordEncoder.encode(teacher.gettPass()));
        teacher.setCreateTime(new Date());
        teacher.setUpdateTime(new Date());
        teacherMapper.insertSelective(teacher);
        list.add(teacher);
        this.saveTeacherRole(list);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
    }

    /**
     * 单个、批量删除
     */
    @Override
    @Transactional
    public ResultJosn delete(List<String> tId) {
        EvaTeacherExample teacherExample = new EvaTeacherExample();
        teacherExample.createCriteria().andTIdIn(tId);
        userRoleService.delByUids(tId);
        teacherMapper.deleteByExample(teacherExample);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "删除成功");
    }

    /**
     * @Title 修改老师信息
     */
    @Override
    @Transactional
    public ResultJosn update(EvaTeacher teacher) {
        if (StringUtils.isBlank(teacher.gettId())) {
            throw new IllegalArgumentException("tId错误！");
        }
        EvaTeacher check = this.checkTeacherNo(teacher.gettNo());
        if (null != check && !(check.gettId()).equals(teacher.gettId())) {
            throw new IllegalArgumentException("教师工号已存在！");
        }
        teacher.settPass(passwordEncoder.encode(teacher.gettPass()));
        teacherMapper.updateByPrimaryKeySelective(teacher);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "修改成功");
    }

    /**
     * @Title 查询全部老师
     * 可以根据教师工号进行模糊查询
     */
    @Override
    public LayuiTableResult select(EvaTeacherVo evaTeacherVo, Integer page, Integer pageSize) {
        LayuiTableResult resultJosn = new LayuiTableResult();
        //构造条件
        EvaTeacherExample example = new EvaTeacherExample();
        example.setOrderByClause("create_time DESC");
        Criteria criteria = example.createCriteria();
        //根据输入的教师编号tName模糊查找
        if (StringUtils.isNotBlank(evaTeacherVo.gettName())) {
            criteria.andTNameLike("%" + evaTeacherVo.gettName() + "%");
        }
        //根据输入的教师工号tno模糊查找
        if (StringUtils.isNotBlank(evaTeacherVo.gettNo())) {
            criteria.andTNoLike("%" + evaTeacherVo.gettNo() + "%");
        }
        //开启分页查找
        PageHelper.startPage(page, pageSize);
        List<EvaTeacherVo> list = teacherVoMapper.selectTdIdAndDName(example);
        PageInfo<EvaTeacherVo> pageInfo = new PageInfo<>(list, pageSize);
        //设置返回前台的格式和数据，如code=0/success，message，查询的总数total，和数据集合data
        resultJosn.setCode(HttpStatus.OK.value());
        resultJosn.setMessage(HttpStatus.OK.getReasonPhrase());
        resultJosn.setCount(pageInfo.getTotal());
        resultJosn.setData(pageInfo.getList());
        return resultJosn;
    }

    /**
     * 根据教师工号查找是否重复
     * @param tNo
     * @return
     */
    public EvaTeacher checkTeacherNo(String tNo) {
        EvaTeacherExample example = new EvaTeacherExample();
        example.createCriteria().andTNoEqualTo(tNo);
        List<EvaTeacher> list = teacherMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return (EvaTeacher) list.get(0);
    }

    @Override
    public ResultJosn selectBytId(String tId) {
        if (StringUtils.isBlank(tId)) {
            throw new IllegalArgumentException("tId错误！");
        }
        EvaTeacher result = teacherMapper.selectByPrimaryKey(tId);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), result);
    }

    /**
     * @Title: saveTeacherRole
     * @Description: 保存教师角色
     * @param: tecs
     * @return: void
     */
    @Async
    @Transactional
    private void saveTeacherRole(List<EvaTeacher> tecs) {
        // 查询出教师唯一标识的角色id
        SysRoleExample example = new SysRoleExample();
        example.createCriteria().andRNameEqualTo("TEACHER");
        List<SysRole> rids = roleMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(rids)) {
            // 先删除
            List<String> tids = tecs.parallelStream().map(EvaTeacher::gettId).collect(Collectors.toList());
            SysUserRoleExample example1 = new SysUserRoleExample();
            example1.createCriteria().andUidIn(tids);
            userRoleMapper.deleteByExample(example1);
            // 插入
            Long roleId = rids.get(0).getrId();
            for (String tid : tids) {
                SysUserRoleKey record = new SysUserRoleKey(tid, roleId);
                userRoleMapper.insert(record);
            }
        }
    }

}
